import React, { useEffect, useState } from "react";
import CanvasRuler from "./CanvasRuler";
import Line from "./Line";

interface ReactSketchRulerProps {
  hLines: Array<number>;
  vLines: Array<number>;
  onLineAdd?: (offset: number, vertical: boolean) => void;
}

export default function ReactSketchRuler(props: ReactSketchRulerProps) {
  const { hLines, vLines, onLineAdd } = props;

  const thick = 16;
  const [width, updateWidth] = useState(482);
  const [height, updateHeight] = useState(482);
  
  const [showIndicator, updateShowIndicator] = useState(false);
  const [indicatorOffset, updateIndicatorOffset] = useState(0);

  useEffect(() => {
    const rect = document
      .querySelector(".react-sketch-ruler")
      .getBoundingClientRect();
    updateWidth(rect.width);
    updateHeight(rect.height);
  }, [hLines, vLines]);

  const onHClick: React.MouseEventHandler<HTMLCanvasElement> = (event) => {
    onLineAdd(event.nativeEvent.offsetX, false);
  };
  const onVClick: React.MouseEventHandler<HTMLCanvasElement> = (event) => {
    onLineAdd(event.nativeEvent.offsetY, true);
  };

  return (
    <div className={"react-sketch-ruler"}>
      <div className={"h-ruler-wrapper"}>
        <CanvasRuler
          start={0}
          vertical={false}
          width={width}
          height={thick}
          canvasConfig={{
            bgColor: "rgba(225,225,225, 0)",
            fontColor: "#7D8694",
            longMarkColor: "#BABBBC", // ruler longer mark color
            shortMarkColor: "#C8CDD0", // ruler shorter mark color
          }}
          onClick={onHClick}
          onMouseEnter={()=>updateShowIndicator(true)}
          onMouseLeave={()=>updateShowIndicator(false)}
          onMouseMove={(event)=>{updateIndicatorOffset(event.nativeEvent.offsetX)}}
        ></CanvasRuler>
        <div className={"lines"}>
          {hLines &&
            hLines.map((l, i) => (
              <Line key={i} vertical={false} value={l} start={0}></Line>
            ))}
        </div>
        {showIndicator && (
          <div className={"indicator"} style={{ left: indicatorOffset }}>
            <span>{indicatorOffset}</span>
          </div>
        )}
      </div>
      <div className={"v-ruler-wrapper"}>
        <CanvasRuler
          start={0}
          vertical={true}
          width={thick}
          height={height}
          canvasConfig={{
            bgColor: "rgba(225,225,225, 0)",
            fontColor: "#7D8694",
            longMarkColor: "#BABBBC", // ruler longer mark color
            shortMarkColor: "#C8CDD0", // ruler shorter mark color
          }}
          onClick={onVClick}
        ></CanvasRuler>
        <div className={"lines"}>
          {vLines &&
            vLines.map((l, i) => (
              <Line key={i} vertical={true} value={l} start={0}></Line>
            ))}
        </div>
      </div>
      <div className={"x-corner"}></div>
    </div>
  );
}
